package phaseutil

import (
	"fmt"

	bkenode "gopkg.openfuyao.cn/bkecommon/cluster/node"

	bkessh "gopkg.openfuyao.cn/cluster-api-provider-bke/pkg/remote"
)

const (
	CheckArchCommand = "echo $(uname -m | sed 's/x86_64/amd64/;s/aarch64/arm64/;s/^unknown$/amd64/')"
)

// NodeToRemoteHost converts node struct to remote host struct
func NodeToRemoteHost(nodes bkenode.Nodes) []bkessh.Host {
	var hosts []bkessh.Host
	for _, node := range nodes.Decrypt() {
		host := bkessh.Host{
			User:     node.Username,
			Address:  node.IP,
			Port:     node.Port,
			Password: node.Password,
			SSHKey:   nil,
			Extra: map[string]string{
				"hostname": node.Hostname,
				"arch":     "unknown",
			},
		}
		hosts = append(hosts, host)
	}
	return hosts
}

// SetRemoteHostArch sets remote host arch
func SetRemoteHostArch(srcHosts []bkessh.Host, stdout map[string]bkessh.CombineOuts) []bkessh.Host {
	for _, host := range srcHosts {
		if v, ok := stdout[host.Address]; ok {
			if v[0].Command == CheckArchCommand && len(v) > 0 {
				host.Extra["arch"] = v[0].Out
			}
		}
	}
	return srcHosts
}

func HostArchExit(hosts []bkessh.Host) []string {
	var hostsExit []string
	for _, host := range hosts {
		if host.Extra["arch"] == "unknown" {
			hostsExit = append(hostsExit, host.Address)
		}
	}
	return hostsExit
}

func HostCustomCmdFunc(host *bkessh.Host) bkessh.Command {
	c := []string{
		fmt.Sprintf("echo %s > /etc/bkeagent/node", host.Extra["hostname"]),
	}
	expectAgent := fmt.Sprintf("/bkeagent_linux_%s", host.Extra["arch"])
	f := []bkessh.File{
		{Src: expectAgent, Dst: "/usr/local/bin/"},
	}
	return bkessh.Command{
		Cmds:   c,
		FileUp: f,
	}
}
